package com.bourse.core.utils;

import java.util.ArrayList;
import java.util.Date;

import org.joda.time.DateMidnight;

import com.bourse.core.exceptions.TimeSerieException;

public class TimeSerie {

	private ArrayList<DateMidnight> dates = new ArrayList<DateMidnight>();
	private ArrayList<Double> datas = new ArrayList<Double>();

	public TimeSerie() {
	}

	public DateMidnight getFirstDate() {
		return dates.get(0);
	}

	public DateMidnight getLastDate() {
		return dates.get(dates.size() - 1);
	}

	public void add(DateMidnight dt, double value) throws TimeSerieException {

		if (dates.size() != 0) {
			for (int i = 0; i < dates.size(); i++) {
				if (dt.isBefore(dates.get(i))) {
					throw new TimeSerieException("Back date exception: " + dt);
				}
			}
			dates.add(dt);
			datas.add(Double.valueOf(value));
		} else {
			dates.add(dt);
			datas.add(Double.valueOf(value));
		}
	}

	public ArrayList<DateMidnight> getDates() {
		return dates;
	}

	public DateMidnight getDate(int idx) {
		return dates.get(idx);
	}

	public double getValue(int idx) {
		return datas.get(idx).doubleValue();
	}

	public boolean exist(Date dt) {
		return dates.contains(dt);
	}

	public void setValue(int idx, double value) {
		datas.set(idx, value);
	}

	public void setValue(Date dt, double value) {
		int idx = dates.indexOf(dt);
		datas.set(idx, value);
	}

	public TimeSerie getTimeSerie(DateMidnight bDate, DateMidnight eDate) throws TimeSerieException {
		TimeSerie returned = new TimeSerie();
		DateMidnight theBDate = null;
		DateMidnight theEDate = null;

		if (bDate == null || bDate.isBefore(dates.get(0))) {
			theBDate = dates.get(0);
		} else {
			theBDate = bDate;
		}

		if (eDate == null) {
			theEDate = dates.get(dates.size() - 1);
		} else {
			theEDate = eDate;
		}

		for (int i = 0; i < dates.size(); i++) {
			if ((theBDate.equals(dates.get(i)) || theBDate.isBefore(dates.get(i)))
					&& (theEDate.equals(dates.get(i)) || theEDate.isAfter(dates.get(i)))) {
				returned.add(dates.get(i), datas.get(i));
			}
		}
		return returned;
	}

	public double getValue(Date dt) {
		int idx = dates.indexOf(dt);
		return datas.get(idx).doubleValue();
	}

	public ArrayList<Double> getValues() {
		return datas;
	}

	public int size() {
		return dates.size();
	}

}
